package com.xk.meeting.controller;

import com.xk.meeting.entity.User;
import com.xk.meeting.service.RegformService;
import com.xk.meeting.service.RegformServiceImpl;
import com.xk.meeting.service.UserService;
import com.xk.meeting.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter({"/apply.jsp","/regform.jsp"})
public class ApplyFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        User user = (User)request.getSession().getAttribute("user");


        String requestURI = request.getRequestURI().toString();

        if (user != null){
            UserService userService = new UserServiceImpl();
            int status = userService.getState(user.getId());
            RegformService regformService = new RegformServiceImpl();
            boolean result = regformService.isExist(user.getId());
            if(requestURI.contains("apply.jsp")) {
                if (result) {
                    if (status == 1) {
                        chain.doFilter(request, response);
                    } else {
                        request.setAttribute("msg2", "您的登记信息正在审核中,请稍后再试!");
                        request.getRequestDispatcher("index.jsp").forward(request,response);
                    }
                } else {
                    request.setAttribute("msg1", "您是第一次预约,请先登记信息");
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                }
            }else {
                if (result) {
                    if(status == -1){
                        chain.doFilter(request,response);
                    }else {
                        request.setAttribute("msg2", "您的登记信息正在审核中,请稍后再试!");
                        request.getRequestDispatcher("index.jsp").forward(request,response);
                    }
                } else {
                    chain.doFilter(request,response);
                }
            }
        }else {
            response.sendRedirect("login.jsp");
        }
    }
    public void init(FilterConfig config) throws ServletException {

    }

}
